<?php

namespace app\api\Service;

use think\Db;
use think\Config;
use app\common\library\Auth;
use addons\epay\library\Service;

class PollingService
{
    // 工单超时未确认后台提醒
    public static function confirmTimeout()
    {
        try{

            $batchSize = 1000; // 每次批量更新的数量
            $expiretime = time() - Config::get('site.confirm_timeout') * 60 ;
            Db::name('order')
                ->where(['is_sure'=>0,'createtime'=>['<',$expiretime]])
                ->chunk($batchSize, function($data) {
                    foreach ($data as $row) {
                        $noticeParams = [
                            'event' => 'confirm_timeout',
                            'params' => array (
                                'receiver_admin_ids' => '',
                                'receiver_admin_group_ids' => '',
                                'order_no' => $row['order_no'],
                            )];
                        \Think\Hook::listen('send_notice', $noticeParams);

                    }
                });
            Db::commit();
            return ['code'=>1,'message'=>'操作成功','data'=>''];
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }


    // 用户超时为点击确认自动确认
    public static function completeTimeout()
    {
        try{

            $batchSize = 1000; // 每次批量更新的数量
            $expiretime = time() - Config::get('site.autocomplete') * 3600;
            Db::name('order')
                ->where(['status'=>2,'updatetime'=>['<',$expiretime],'finish_annex'=>['<>','']])
                ->chunk($batchSize, function($data) {
                    foreach ($data as $row) {
                        // 进行更新
                        Db::name('order')->where('id', $row['id'])->update(['status'=>'3',
                            'updatetime'=>time()]);

                        // 订单完成给师傅提成
                        $master_id = $row['master_id'];
                        $platform_commission = Config::get("site.platform_commission");

                        if($row['type'] == 'install'){
                            $orderInstall = \app\admin\model\OrderInstall::where(['order_id'=>$row['id']])->field('price,extra_money')->find();
                            $price = $orderInstall['price'];
                        }
                        if($row['type'] == 'repair'){
                            $orderRepair = \app\admin\model\OrderRepair::where(['order_id'=>$row['id']])->field('inspection_fee')->find();
                            $price = $orderRepair['inspection_fee'];
                        }
                        $money = $price * (1 - $platform_commission / 100);
                        \app\common\model\User::money($money,$master_id,"订单{$row['order_no']}完成提成");

                    }
                });
            Db::commit();
            return ['code'=>1,'message'=>'操作成功','data'=>''];
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }

    
    // 用户超时为点击确认自动确认
    public static function withdrawalTimeout()
    {
        
        $filePath = ROOT_PATH . '/public/cert/wechat/';
                        // $filePath = ROOT_PATH . '/addons/epay/certs/';
                        $payment = [
                            'certPem' => $filePath . 'apiclient_cert.pem',
                            'keyPem' => $filePath . 'apiclient_key.pem',
                            'wx_certificates' => $filePath . 'pub_key.pem',
                        ];
                        
                        // 进行更新
                        $order_code = \app\admin\model\Order::where(['id'=>271])->value('order_no');
                        $res = self::getMchPayRecord($order_code,$payment);
                        return $res;
        
        
        
        
        try{

            $batchSize = 1000; // 每次批量更新的数量
            Db::name('user_withdrawal_appply')
                ->where(['status'=>1,'package_info'=>['<>',' ']])
                ->chunk($batchSize, function($data) {
                    foreach ($data as $row) {
                        
                        $filePath = ROOT_PATH . '/public/cert/wechat/';
                        // $filePath = ROOT_PATH . '/addons/epay/certs/';
                        $payment = [
                            'certPem' => $filePath . 'apiclient_cert.pem',
                            'keyPem' => $filePath . 'apiclient_key.pem',
                            'wx_certificates' => $filePath . 'pub_key.pem',
                        ];
                        
                        // 进行更新
                        $order_code = \app\admin\model\Order::where(['id'=>$row['order_id']])->value('order_no');
                        $res = self::getMchPayRecord($order_code,$payment);
                        return $res;
                    }
                });
            Db::commit();
            return ['code'=>1,'message'=>'操作成功','data'=>''];
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'message'=>$e->getMessage(),'data'=>''];
        }
    }
    
    
    
    /**
     * @param $str
     * @param $payment
     * @功能说明:根据平台证书加密
     */
     public function getEncrypt($str,$payment) {
        //$str是待加密字符串
        $public_key_path = $payment['wx_certificates'];

        if(empty($public_key_path)){

            return '';
        }

        $public_key = file_get_contents($public_key_path);

        $encrypted = '';

        if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
            //base64编码
            $sign = base64_encode($encrypted);
        } else {
            throw new Exception('encrypt failed');
        }
        return $sign;
    }


   /**
     * @功能说明:查询转账记录
     */
    public static function getMchPayRecord($order_code,$payment){

        $url = 'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills/out-bill-no/'.$order_code;
        //请求方式
        $token  = self::getToken([],$payment,'GET',$url);

        $res    = self::https_request($url,[],$token);//发送请求

        $resArr = json_decode($res,true);

        return $resArr;
    }

	 public static function https_request($url,$data,$token)
	    {
	        $curl = curl_init();
	        curl_setopt($curl, CURLOPT_URL, (string)$url);
	        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	        if (!empty($data)) {
	            curl_setopt($curl, CURLOPT_POST, 1);
	            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	        }
	        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	        //添加请求头
	        $headers = [
	            'Authorization:WECHATPAY2-SHA256-RSA2048 ' . $token,
	            'Accept: application/json',
	            'Content-Type: application/json; charset=utf-8',
	            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
	        ];
	        if (!empty($headers)) {
	            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	        }
	        $output = curl_exec($curl);
	        curl_close($curl);
	        return $output;
	    }


 	/**
     * @param $payment
     * @功能说明:获取证书序列号
     */
    public static function get_Certificates($payment)
    {

        $platformCertificateFilePath = $payment['wx_certificates'];

        if(empty($platformCertificateFilePath)){

            return '';
        }

        $a = openssl_x509_parse(file_get_contents($platformCertificateFilePath));

        return !empty($a['serialNumberHex'])?$a['serialNumberHex']:'';
    }


	/**
     * POST 请求
     */
    public static function http_post($url,$data,$token,$payment,$Wechatpay=0){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, (string)$url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //添加请求头
        $headers = [

            'Authorization:WECHATPAY2-SHA256-RSA2048 '.$token,
            'Accept: application/json',
            'Content-Type: application/json; charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        //需要加密
        if($Wechatpay==1){

            $certificates = self::get_Certificates($payment);

            $headers[] = 'Wechatpay-Serial:'.$certificates;
        }
        if(!empty($headers)){

            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
    }


/**
     * @param $pars
     * @param $payment
     * @功能说明:获取token
     */
    public static function getToken($pars,$payment,$http_method='POST',$usrl_data='')
    {

        $url = !empty($usrl_data)?$usrl_data:'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills';
       // $http_method = 'POST';//请求方法（GET,POST,PUT）
        $timestamp = time();//请求时间戳
        $url_parts = parse_url($url);//获取请求的绝对URL
        $nonce = $timestamp . rand(10000, 99999);//请求随机串
        $body = !empty($pars)?json_encode((object)$pars):'';//请求报文主体
        $stream_opts = [
            "ssl" => [
                "verify_peer" => false,
                "verify_peer_name" => false,
            ]
        ];
        $apiclient_cert_path = $payment['certPem'];
        $apiclient_key_path  = $payment['keyPem'];
        $apiclient_cert_arr = openssl_x509_parse(file_get_contents($apiclient_cert_path, false, stream_context_create($stream_opts)));
        $serial_no = '4C59EB16EAA829C2E0DEC4244E6C41633768D1DF';//证书序列号
        $mch_private_key = file_get_contents($apiclient_key_path, false, stream_context_create($stream_opts));//密钥
        $merchant_id = '1709517563';//商户id
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $message = $http_method . "\n" .
            $canonical_url . "\n" .
            $timestamp . "\n" .
            $nonce . "\n" .
            $body . "\n";
        openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');

        $sign = base64_encode($raw_sign);//签名
        $schema = 'WECHATPAY2-SHA256-RSA2048';
        $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
        return $token;

    }
    
    
    
    
}